package nccloud.sso.util;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;



/**
 * AES加密解密，Base64转码
 */
public class AESUtil {

	
	private static final String KEY = DesUtil.KEY;
	
	/**
     * 将传入的明文转换为密文
     * 
     * @param str 明文字符串
     * @return 加密后的密文
	 * @throws BadPaddingException 
	 * @throws IllegalBlockSizeException 
     */
	public static String encode(String str) throws Exception {
		byte[] result = null;
		KeyGenerator kgen = KeyGenerator.getInstance("AES");
		SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
		random.setSeed(KEY.getBytes());
		kgen.init(128, random);
		SecretKey secretKey = kgen.generateKey();
		byte[] enCodeFormat = secretKey.getEncoded();
		SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
		
		// 创建密码器
		Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
		cipher.init(Cipher.ENCRYPT_MODE, key);
		byte[] byteContent = str.getBytes();
		result = cipher.doFinal(byteContent);
		
		return new String(Base64.encode(result));
	}
	
	/**
     * 将传入的密文转换为明文
     * 
     * @param str 密文字符串
     * @return 解密后的明文
	 * @throws NoSuchPaddingException 
	 * @throws NoSuchAlgorithmException 
     */
	public static String decode(String str) throws Exception {
		byte[] result = null;
		byte[] content = Base64.decode(str.getBytes());
		KeyGenerator kgen = KeyGenerator.getInstance("AES");
		SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
		random.setSeed(KEY.getBytes());
		kgen.init(128, random);
		SecretKey secretKey = kgen.generateKey();
		byte[] enCodeFormat = secretKey.getEncoded();
		SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
		
		// 创建密码器
		Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
		cipher.init(Cipher.DECRYPT_MODE, key);
		result = cipher.doFinal(content);
		return new String(result);
	}
	

	public static void main(String[] args) throws Exception {
		String encode = encode("lq|1610533558132|11f7f609b92130e3");
		System.out.println(encode);
		System.out.println(decode("no8yog4UD+yccFd28TI0iHH5rSKeb+dCwkPoKgZ3PupkF+Hlf8FuT69aPfFz3OBZB+SH9UJWXddUKVJxGfb5eg=="));
	}
	
}
